package com.ch.android.baselib

import android.content.Context
import android.content.SharedPreferences
import kotlin.jvm.Throws

/**
 * Author: conghao
 * Date: 2023/12/29 16:45
 * Description: SpUtil
 */
object SpUtil {
    const val SHARED_PREFERENCES_NAME = "look_for"
    const val KEY_USER_ID = "userId"
    const val KEY_USER_NAME = "username"
    const val KEY_SESSION_ID = "sessionId"
    const val KEY_HEAD_PIC = "headPic"
    const val KEY_NICKNAME = "nickname"
    private var sp: SharedPreferences? = null

    fun initialize(context: Context) {
        if (sp != null) {
            return
        }
        sp = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
    }

    @Throws(RuntimeException::class)
    fun getSP(): SharedPreferences {
        if (sp == null) {
            throw RuntimeException("SpUtil not initialize")
        }
        return sp!!
    }

    fun SharedPreferences.getUserId() = getInt(KEY_USER_ID, 0)
    fun SharedPreferences.setUserId(userId: Int) = edit().putInt(KEY_USER_ID, userId).apply()

    fun SharedPreferences.getUsername() = getString(KEY_USER_NAME, "")
    fun SharedPreferences.setUsername(username: String) = edit().putString(KEY_USER_NAME, username).apply()

    fun SharedPreferences.getNickname() = getString(KEY_NICKNAME, "")
    fun SharedPreferences.setNickname(nickname: String) = edit().putString(KEY_NICKNAME, nickname).apply()


    fun SharedPreferences.getSessionId() = getString(KEY_SESSION_ID, "")!!
    fun SharedPreferences.setSessionId(sessionId: String) = edit().putString(KEY_SESSION_ID, sessionId).apply()

    fun SharedPreferences.getHeadPic() = getString(KEY_HEAD_PIC, "")
    fun SharedPreferences.setHeadPic(userAvatar: String) = edit().putString(KEY_HEAD_PIC, userAvatar).apply()

}

